<?php
/**
 *  地址管理
*/

namespace app\admin\service;
use app\admin\model\Address as AddressModel;
use app\admin\model\RegionCity;
use app\admin\model\RegionCountry;
use app\facade\Basic;

class Address extends BaseService
{

    /**
     *  地址列表
    */
    public function list($param)
    {
        $where['user_id'] = $param['user_id'];
        $result = AddressModel::where($where)
            ->field('id,first_name,last_name,email,phone,address,type,is_default,country_id,city_id,country_name,city_name,zip_code,state,state_id,company,address2,remark')
            ->order('is_default DESC')
            ->paginate($param['listRows']);

        return Basic::paginator(0,'成功',$result);
    }

    /**
     *  获取地址列表
     * @param $param
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 2024-11-18 11 38 17
     * author: jiang
     */
    public function getList($param, $page = 1, $limit = 10)
    {
        $where = [];
        $arrData = ['code' => 0, 'message' => 'success'];
        if ($param['phone']) {
            $where[] = ['phone', 'like', '%' . $param['phone'] . '%'];
        }
        if($param['name']){
            $where[] = ['first_name|last_name', 'like', '%' . $param['name'] . '%'];
        }
        if($param['user_id']){
            $where[] = ['user_id', '=', $param['user_id']];
        }
        if($param['type']){
            $where[] = ['type', '=', $param['type']];
        }
        $oAddressModel = AddressModel::where($where);
        $total = $oAddressModel->count();
        $result = $oAddressModel
                ->alias('a')
                ->field('a.*,a.country_id as to_nation')
                ->page($page, $limit)
                ->select();
        $arrData['data'] = ['list' => $result->toArray(),'total' => $total];
        return $arrData;
    }


    /**
     *  获取默认地址
    */
     public function getDefaultAddress($param)
     {
         $where['user_id'] = $param['user_id'];
         $where['is_default'] = 1;
         $result = AddressModel::where($where)->field('id,first_name,last_name,email,phone,address,remark,country_id,city_id,country_name,city_name,zip_code,state,state_id,company,address2,remark')->find();
         if (!$result) {
             return [];
         } else {
             return $result->toArray();
         }
     }

    /**
     *  获取地址详情
    */
    public function detail($param)
    {
        $where['user_id'] = $param['user_id'];
        $where['id'] = $param['id'];


        $result = AddressModel::where($where)
            ->field('id,first_name,last_name,email,phone,address,is_default,country_id,city_id,country_name,city_name,zip_code,state,state_id,company,address2,remark')
            ->find();

        if( !$result ) {
            return Basic::data(1,'address.addressNotFound');
        }

        return Basic::data(0,'common.success',$result);
    }


    /**
     *  添加编辑地址
    */
    public function save($param)
    {

        /* 获取国家名称 */
        $country = RegionCountry::where('id',$param['country_id'])->field('id,name')->find();
        if( !$country ){
            return Basic::data(1,'address.countryIdAlreadyExists');
        }
        $param['country_name'] =  $country->name;
        $param['country_id'] =  $country->id;

        // 城市和州
        if( !empty($param['city_id']) ) {

            $City = RegionCity::where('id',$param['city_id'])->field('id,name,state,state_code')->find();

            if( !$City ){
                return Basic::data(1,'address.cityIdAlreadyExists');
            }

            $param['city_id'] =  $City->id;
            $param['city_name'] =  $City->name;
            $param['state'] =  $City->state;
            $param['state_id'] =  $City->state_code;

        }


        if ( empty($param['id']) ) {

            $param['create_time'] = date('Y-m-d H:i:s',time());
            $where['user_id'] = $param['user_id'];
            $where['address'] = $param['address'];
            $where['type'] = $param['type'];

            $result = AddressModel::where($where)->field('id')->find();

            /* 地址以存在 */
            if( $result ){
                return Basic::data(1,'address.addressAlreadyExists');
            }

            $result = AddressModel::create($param);
            $this->logger->logOperation($result->id,'address','添加', '添加地址');


            if( $result ){

                /* 设置默认 */
                if( $param['is_default'] == 1 ) {
                    $this->addDefault($result);
                }

                return Basic::data(0,'address.savedSuccessfully');
            } else {
                return Basic::data(1,'address.saveFailed');
            }

        } else {

            $where['id'] = $param['id'];
            $where['user_id'] = $param['user_id'];
            $result = AddressModel::where($where)->find();


            /* 地址以存在 */
            if( !$result ){
                return Basic::data(1,'address.addressNotExist');
            }

            $param['update_time'] = date('Y-m-d H:i:s',time());

            $result = AddressModel::update($param);
            $this->logger->logOperation($result->id,'address','修改', '修改地址');

            if( $result ){

                /* 设置默认 */
                if( $param['is_default'] == 1 ) {
                    $this->addDefault($result);
                }

                return Basic::data(0,'address.updateSuccessfully');
            } else {
                return Basic::data(1,'address.updateFailed');
            }

        }

    }

    /**
     *  添加修改设置默认地址
    */
    public function addDefault($data)
    {

        AddressModel::where('user_id',$data->user_id)->where('is_default',1)->update([
            'is_default' => 0
        ]);

        AddressModel::where('user_id',$data->user_id)->where('id',$data->id)->update([
            'is_default' => 1
        ]);
        $this->logger->logOperation($data->id,'address','设置默认', '交换默认地址');
    }


    /**
     *  设置默认地址
    */
    public function setDefault($param)
    {
        $where['user_id'] = $param['user_id'];
        $where['id'] = $param['id'];

        $result = AddressModel::where($where)->find();

        if( !$result ) {
            return Basic::data(1,'address.addressNotFound');
        }

        /* 修改默认 */
        AddressModel::where('user_id',$param['user_id'])
            ->update([
            'is_default' => 0
        ]);

        $result =  AddressModel::where($where)->update([
                'is_default' => 1
            ]);


        if( $result ){
            $this->logger->logOperation($result->id,'address','设置默认', '设置默认地址');
            return Basic::data(0,'address.settingSuccessful');
        } else {
            return Basic::data(1,'address.settingFailed');
        }

    }

    /**
     *  删除地址
     */
    public function del($param)
    {
        $where['user_id'] = $param['user_id'];
        $where['id'] = $param['id'];

        $result = AddressModel::where($where)->find();

        if( !$result ) {
            return Basic::data(1,'address.addressNotFound');
        }



        $result =  AddressModel::where($where)->delete();

        if( $result ){
            $this->logger->logOperation($param['id'],'address','删除', '删除地址');
            return Basic::data(0,'address.deleteSuccessful');
        } else {
            return Basic::data(1,'address.deleteFailed');
        }

    }

}
